package com.example.basic.utils;

import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.pm.ResolveInfo;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.PopupWindow;

import androidx.core.content.pm.ShortcutInfoCompat;
import androidx.core.content.pm.ShortcutManagerCompat;
import androidx.core.graphics.drawable.IconCompat;


import com.example.basicsharedlib.R;

import java.util.List;

public class ShortcutTools {

    private static String AUTHORITY = "";

    private static final String TAG = "ShortcutTools";
    //期望的Icon大小
    public static final int DESIRED_SIZE_PX = 200;
    //上下文对象
    private Context mContext;
    //设置给快捷方式图标的Icon
    private Bitmap mIcon;
    //快捷方式的标题
    private String mTitle;
    //目标网址的url
    private String mUrl;
    /*
    适配Android 8.0及以上的方式  需要一个Id  这里查重使用的方式是 标题对比  所以为了适配低版本: mId = mTitle
     */
    private String mId;
    //点击快捷方式希望启动的意图
    private Intent mLauncherIntent;
    private boolean mNeedRecycle = false;

    private static final String SHOW_DIALOG = "showdialog";
    private boolean isNeedShowDialog;
    private SharedPreferences mSharedPreferences;

    //创建时各种情况的回调
    private CallBack mCallBack = new CallBack() {

        @Override
        public void repeatCreate(String title, String id) {
//            ToastManager.getInstance().showText(mContext,mContext.getString(R.string.zcsd_toast_shortcut_already_exists));
            recycleBitmap();
        }

        @Override
        public void createSuccess(String title, String id) {
            mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext.getApplicationContext());
            isNeedShowDialog = mSharedPreferences.getBoolean(SHOW_DIALOG, true);
            if (isNeedShowDialog) {
                showTipsDialog(mContext);
            }

            recycleBitmap();
        }

        @Override
        public void noSupportedPinShortcut() {
//            ToastManager.getInstance().showText(mContext,mContext.getString(R.string.zcsd_toast_device_no_support));
            recycleBitmap();
        }
    };
//    private CopycatAlertDialogBuilder mBuilder;

    private ShortcutTools(Context context) {
        mContext = context;
    }

    public static ShortcutTools init(Context context) {
        return new ShortcutTools(context);
    }

    public ShortcutTools setTitleAndUrl(String title, String targetUrl) {
        fixTitle(title);
        fixUrl(targetUrl);
        return this;
    }

    public ShortcutTools setIcon(Bitmap icon) {
        mIcon = icon;
        return this;
    }

    public void showTipsDialog(Context context) {

//        mBuilder = (CopycatAlertDialogBuilder) SkinAlertDialogFactory.createCopycatBuilder(context);
//        mBuilder.setOnKeyListener((dialog, keyCode, event) -> true);
//        mBuilder.setCanceledOnTouchOutside(true);
//        final View view = View
//                .inflate(context, R.layout.zcsd_dailog_shortcut, null);
//        mBuilder.setTitle(mContext.getText(R.string.zcsd_dialog_shortcut_title));
//        mBuilder.setView(view);
//        mBuilder.setButtonContainerMarginTop(context.getResources().getDimensionPixelSize(R.dimen.dp_10));

//        StyleSpan span = new StyleSpan(Typeface.BOLD);
//        TextView tvDescription1 = view.findViewById(R.id.tv_description_1);
//        String tips1 = mContext.getString(R.string.zcsd_dialog_shortcut_tip1);
//        String[] splitTips1 = tips1.split("：");
//        SpannableString description1 = new SpannableString(tips1);
//
//        description1.setSpan(span,0,splitTips1[0].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        tvDescription1.setText(description1);
//
//        TextView tvDescription2 = view.findViewById(R.id.tv_description_2);
//        String tips2 = mContext.getString(R.string.zcsd_dialog_shortcut_tip2);
//        String[] splitTips2 = tips2.split("：");
//        SpannableString description2 = new SpannableString(tips2);
//        description2.setSpan(span,0,splitTips2[0].length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        tvDescription2.setText(description2);
//
//        mBuilder.setPositiveButton(mContext.getString(R.string.zcsd_setting), (dialog, which) -> {
//            mBuilder.dismiss();
//            openSetting(context);
//        });
//        mBuilder.setNegativeButton(mContext.getString(R.string.zcsd_cancel), (dialog, which) -> {
//            mBuilder.dismiss();
//        });
//        mBuilder.setOnDismissListener(dialog -> {
//            if(!isNeedShowDialog) {
//                mSharedPreferences.edit().putBoolean(SHOW_DIALOG,isNeedShowDialog).apply();
//            }
//        });
//
//        CheckBox cb = view.findViewById(R.id.cb_auth_read);
//        cb.setOnCheckedChangeListener((buttonView, isChecked) -> isNeedShowDialog = !isChecked);
//        mBuilder.show();

    }

    //在这个方法里面可以对传入的Url做一些处理
    private void fixUrl(String targetUrl) {
        mUrl = targetUrl;
    }

    public ShortcutTools setCallback(CallBack callback) {
        handleCallBack(callback);
        mCallBack = callback;
        return this;
    }

    private void handleCallBack(CallBack callback) {
        mCallBack = callback;
    }

    public void creatShortcut() {
        //检测是否重复添加
        if (hasShortCut(mContext, mId)) {
            if (mCallBack != null) {
                mCallBack.repeatCreate(mTitle, mId);
            }
            return;
        }
        //处理图标
        fixIcon();
        //构建请求意图
        buildLauncherIntent();
        //创建图标
        createShortcut();
        //处理结果
        handleResult();
    }

    private void buildLauncherIntent() {
        Class cls = null;
        try {
            cls = Class.forName("org.chromium.chrome.browser.ChromeTabbedActivity");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        mLauncherIntent = new Intent(mContext, cls);
        //action必须设置，不然报错
        mLauncherIntent.setAction(Intent.ACTION_VIEW);
        mLauncherIntent.setData(Uri.parse(mUrl));
    }

    private void handleResult() {
        if (mCallBack != null) {
            mCallBack.createSuccess(mTitle, mId);
        }
    }

    //在这个方法里面可以对传入的title做一些处理
    private void fixTitle(String title) {
        if (TextUtils.isEmpty(title)) {
            mTitle = "";
        } else {
            mTitle = title;
        }
        mId = mTitle;
    }

    //创建桌面快捷方式
    private void createShortcut() {
        if (ShortcutManagerCompat.isRequestPinShortcutSupported(mContext)) {
            ShortcutInfoCompat info = new ShortcutInfoCompat.Builder(mContext, mId)
                    .setIcon(IconCompat.createWithBitmap(mIcon))
                    .setShortLabel(mTitle)
                    .setIntent(mLauncherIntent)
                    .build();

            //当添加快捷方式的确认弹框弹出来时，将被回调
            Intent intent = new Intent(mContext, ShortcutResultReceiver.class);
            PendingIntent shortcutCallbackIntent = PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            ShortcutManagerCompat.requestPinShortcut(mContext, info, shortcutCallbackIntent.getIntentSender());
        } else {
            //不支持此功能
            if (mCallBack != null) {
                mCallBack.noSupportedPinShortcut();
            }
        }
    }

    private void recycleBitmap() {
        if (mNeedRecycle && mIcon != null && !mIcon.isRecycled()) {
            mIcon.recycle();
        }
    }

    private void fixIcon() {
        mIcon = createHomeScreenIconFromWebIcon(mTitle, mIcon, mContext);
    }

    public interface CallBack {
        void repeatCreate(String title, String id);

        void createSuccess(String title, String id);

        void noSupportedPinShortcut();
    }

    /*--------------Pop弹窗,此处用于弹出创建快捷方式的弹出------------*/
    public static void show(View view, View.OnClickListener clickListener, PopupWindow.OnDismissListener dismissListener) {
//        View mPopView = LayoutInflater.from(view.getContext()).inflate(R.layout.zcsd_popup_send_to_desktop, null);
//        LinearLayout llSendToDesktop = mPopView.findViewById(R.id.ll_send_to_desktop);
//        PopupWindow mPopupWindow = new PopupWindow(mPopView,
//                LinearLayout.LayoutParams.WRAP_CONTENT,
//                LinearLayout.LayoutParams.WRAP_CONTENT);
//        mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//        mPopupWindow.setOutsideTouchable(true);
//        // mpopupWindow.setBackgroundDrawable(background);
//        llSendToDesktop.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                mPopupWindow.dismiss();
//                clickListener.onClick(v);
//            }
//        });
//
//        int[] location = new int[2];
//        view.getLocationInWindow(location);
//        mPopupWindow.setContentView(mPopView);
//        mPopupWindow.setOnDismissListener(dismissListener);
//        mPopupWindow.showAsDropDown(view,view.getWidth()/2,-view.getHeight()/2);

    }

    /*--------------Android 8.0及以上弹窗创建快捷方式时会回调（产商定制化太严重，此方式基本无效）------------*/
    public static class ShortcutResultReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
        }
    }

    /*--------------检查当前桌面快捷方式是否已经存在（已适配）------------*/

    private boolean hasShortCut(Context context, String title) {
        boolean hasShortCut = false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            ShortcutManager shortcutManager = (ShortcutManager) context.getSystemService(Context.SHORTCUT_SERVICE);
            for (ShortcutInfo shortcut : shortcutManager.getPinnedShortcuts()) {
                if (title.equals(shortcut.getId())) {
                    hasShortCut = true;
                    break;
                }
            }
        } else {
            if (null == context || TextUtils.isEmpty(title))
                return false;

            if (TextUtils.isEmpty(AUTHORITY))
                AUTHORITY = getAuthorityFromPermission(context);

            if (!TextUtils.isEmpty(AUTHORITY)) {
                try {
                    final Uri CONTENT_URI = Uri.parse(AUTHORITY);
                    final Cursor c = context.getContentResolver().query(CONTENT_URI, null,
                            "title=?", new String[]{title}, null);
                    if (c != null && c.getCount() > 0) {
                        hasShortCut = true;
                    }
                    if (null != c && !c.isClosed())
                        c.close();
                } catch (Exception e) {
                    Log.e(TAG, e.getMessage());
                }
            }
        }
        return hasShortCut;
    }

    private String getCurrentLauncherPackageName(Context context) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        ResolveInfo res = context.getPackageManager().resolveActivity(intent, 0);
        if (res == null || res.activityInfo == null) {
            // should not happen. A home is always installed, isn't it?
            return "";
        }
        if (res.activityInfo.packageName.equals("android")) {
            return "";
        } else {
            return res.activityInfo.packageName;
        }
    }

    private String getAuthorityFromPermissionDefault(Context context) {
        return getThirdAuthorityFromPermission(context, "com.android.launcher.permission.READ_SETTINGS");
    }

    private String getThirdAuthorityFromPermission(Context context, String permission) {
        if (TextUtils.isEmpty(permission)) {
            return "";
        }

        try {
            List<PackageInfo> packs = context.getPackageManager().getInstalledPackages(PackageManager.GET_PROVIDERS);
            if (packs == null) {
                return "";
            }
            for (PackageInfo pack : packs) {
                ProviderInfo[] providers = pack.providers;
                if (providers != null) {
                    for (ProviderInfo provider : providers) {
                        if (permission.equals(provider.readPermission) || permission.equals(provider.writePermission)) {
                            if (!TextUtils.isEmpty(provider.authority)// 精准匹配launcher.settings，再一次验证
                                    && (provider.authority).contains(".launcher.settings"))
                                return provider.authority;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private String getAuthorityFromPermission(Context context) {
        // 获取默认
        String authority = getAuthorityFromPermissionDefault(context);
        // 获取特殊第三方
        if (authority == null || authority.trim().equals("")) {
            String packageName = getCurrentLauncherPackageName(context);
            packageName += ".permission.READ_SETTINGS";
            authority = getThirdAuthorityFromPermission(context, packageName);
        }
        // 还是获取不到，直接写死
        if (TextUtils.isEmpty(authority)) {
            int sdkInt = Build.VERSION.SDK_INT;
            if (sdkInt < 8) { // Android 2.1.x(API 7)以及以下的
                authority = "com.android.launcher.settings";
            } else if (sdkInt < 19) {// Android 4.4以下
                authority = "com.android.launcher2.settings";
            } else {// 4.4以及以上
                authority = "com.android.launcher3.settings";
            }
        }
        authority = "content://" + authority + "/favorites?notify=true";
        return authority;
    }

    /*--------------引导用户打开允许创建桌面快捷方式的入口（需适配各大产商）------------*/
    public static void openSetting(Context context) {
        String model = Build.MODEL;
        String manufacturer = Build.MANUFACTURER;
        if (manufacturer.equalsIgnoreCase("oppo") && model.equalsIgnoreCase("PDBM00")) {
            openOppoShortcutSetting(context,"com.oppo.launcher","com.oppo.launcher.shortcut.ShortcutSettingsActivity");
        } else {
            openDefaultSettings(context);
        }
    }

    private static void openDefaultSettings(Context context) {
        //默认设置界面
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    private static void openOppoShortcutSetting(Context context, String packageName, String clsPath) {
        Intent intent = new Intent();
        ComponentName cm = new ComponentName(packageName, clsPath);
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");
        context.startActivity(intent);
    }

    /*--------------图标处理------------*/
    private Bitmap createHomeScreenIconFromWebIcon(String title, Bitmap webIcon, Context context) {

        if (webIcon != null) {
            return webIcon;
        }

        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        int maxInnerSize = am.getLauncherLargeIconSize();
        Bitmap bitmap = null;

        try {
            bitmap = Bitmap.createBitmap(maxInnerSize, maxInnerSize, Bitmap.Config.ARGB_8888);
        } catch (OutOfMemoryError e) {
            Log.e(TAG, "OutOfMemoryError while creating bitmap for home screen icon.");
//            return BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher);
        }

        //做空处理
        Canvas canvas = new Canvas(bitmap);
        Paint mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBackgroundPaint.setColor(Color.parseColor("#A7B4FA"));
        canvas.drawRoundRect(new RectF(0, 0, maxInnerSize, maxInnerSize), 20, 20, mBackgroundPaint);

        Paint textPaint = new Paint();          // 创建画笔
        textPaint.setColor(Color.BLACK);        // 设置颜色
        textPaint.setStyle(Paint.Style.FILL);   // 设置样式
        textPaint.setTextSize(30);              // 设置字体大小
        textPaint.setFakeBoldText(true);        //设置粗体
        String displayText = title.substring(0, Math.min(4, title.length()));
        Rect rect = new Rect();
        textPaint.getTextBounds(displayText, 0, displayText.length(), rect);
        canvas.drawText(displayText, (maxInnerSize - rect.width()) / 2, (maxInnerSize + rect.height()) / 2, textPaint);
        mNeedRecycle = true;
        return bitmap;
    }


}
